# coding=utf-8
from locale import *
import sys
import datetime
from selenium import webdriver
from selenium.webdriver.firefox.firefox_profile import FirefoxProfile
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from bs4 import BeautifulSoup


def get_mac_address():
    import uuid
    node = uuid.getnode()
    mac = uuid.UUID(int=node).hex[-12:]
    return mac


def validate_mac_address():
    import urllib.request
    f = urllib.request.urlopen('http://amazon-ceping.xunhuanle.com/publicwelcome/getallmacaddress')
    ret_content_bytes = f.read()
    ret_content_str = ret_content_bytes.decode()
    return ret_content_str


mac_address = get_mac_address()
print("Your macaddress is below:")
print(mac_address)
validation_content = validate_mac_address()
if mac_address not in validation_content:
    print("Please submit your unicode '"+mac_address+"' to administrator!!!")
    sys.exit()


file_name_output = "handler_link_"+datetime.datetime.now().strftime('%Y-%m-%d_%H_%M_%S')+".xls"

file_name_input = input("Input Will Import Link File Name:")
print("Import Link File Name is:", file_name_input)

# 读取文件
setlocale(LC_NUMERIC, 'English_US')

# 设置不加载图片
firefoxProfile = FirefoxProfile()
firefoxProfile.set_preference('permissions.default.image', 2)
firefoxProfile.set_preference('dom.ipc.plugins.enabled.libflashplayer.so', 'false')
driver = webdriver.Firefox(firefoxProfile)

file = open(file_name_input, 'r')
for line in file:
    url_list = line.split('\t')
    url = url_list[0]
    driver.get(url.strip())
    soup = BeautifulSoup(driver.page_source, "html.parser")
    all_data_defaultAsin = soup.select('li[data-defaultasin]')
    if len(all_data_defaultAsin) == 0:
        # 有添加到购物车的去掉
        add_to_cart_ele = soup.select_one('#add-to-cart-button')
        if add_to_cart_ele is None:
            print("NEED URL:"+url)
            file_output = open(file_name_output, 'a')
            file_output.writelines(line)
            file_output.close()
        else:
            print("NOT NEED URL:" + url)
    else:
        print("NOT NEED URL:"+url)
file.close()
driver.quit()


